# -*- coding: utf-8 -*-
import re
from optparse import OptionParser


# This com

def Compile(filename, data):
	# make the regex for finding all the commands
	regex = re.compile("(([SIDRWJENsidrwjenQ]) ([0-9-]*))")
	
	# Search all labels, and localize them, then calculate the relative position.
	lines = data.splitlines()
	labels = []

	for line in lines:
		label = re.findall("(\w+):", line)
		if len(label) != 0:
			labels.append(label[0])
		

	preCompiled = []

	for label in labels:
		# first find the line where the label refers to.
		for i in range(len(lines)):
			line = lines[i]
			if label+":" in line:
				start = i
				break
	
		# then replace the label with the integer. (Check if in range of signed byte)
		for i in range(len(lines)):
			line = lines[i]
			if label in line:
				if ":" not in line:
					op = regex.findall(line)[0][1]
					lines[i] = op + " " + str(start - i)
	
	# Drop all the useless lines.
	for line in lines:
		preCompiled.append(line)
			
	data =  '\n'.join(preCompiled)

	def byte(integer):
		if integer <= 127 or integer >= -128:
			if integer < 0:
				return chr(256+integer)
			else:
				return chr(integer)
		return "error"

	with open("%s.clb" %filename, "wb") as outFile:
		for com in regex.findall(data):
			op  = com[1]		# the operation
			val = int(com[2])		# the value
	
			outFile.write("%s%s" %(op, byte(val)))
	
		
if __name__ == "__main__":
	parser = OptionParser()
	parser.add_option("-f", "--file", dest="filename",
		              help="write report to FILE", metavar="FILE")

	(options, args) = parser.parse_args()
	
	filename = options.filename
	data = open(filename).read()
	Compile(filename.split('.')[0], data)
	
	

